<template>
  <div class="common-wrapper">
    <div class="common-title">温湿度历史数据查询</div>
    <div class="common-main">
      <div
        style="
          display: flex;
          justify-content: space-between;
          white-space: nowrap;
        "
      >
        <el-form
          ref="search"
          class="common-search"
          :inline="true"
          :rules="searchRules"
          :model="search"
          :show-message="false"
        >
          <el-form-item>
            <el-select
              v-model="search.cj"
              placeholder="选择车间"
              size="small"
              clearable
            >
              <el-option
                v-for="(item, index) in cjOption"
                :key="index"
                :label="item.cj"
                :value="item.cj"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="search.gongxu"
              placeholder="选择工序"
              size="small"
              clearable
            >
              <el-option
                v-for="(item, index) in gxOption"
                :key="index"
                :label="item['key_value']"
                :value="item['key_value']"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="ct">
            <el-select
              v-model="search.ct"
              placeholder="选择车台范围"
              size="small"
              multiple
              clearable
              class="mul-selection"
              popper-class="mul-select"
              collapse-tags
            >
              <el-option
                v-for="(item, index) in equipOption"
                :key="index"
                :label="item.dictValue + '号'"
                :value="item.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="startTime">
            <el-date-picker
              size="small"
              v-model="time"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd hh:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <div>
            <el-button type="primary" size="small" @click="searchNow"
              >查询</el-button
            >
          </div>
        </el-form>
        <div class="show-type">
          <el-radio
            v-model="showType"
            label="table"
            border
            size="small"
            class="toggle-btn"
            >温湿度历史数据</el-radio
          >
          <el-radio
            v-model="showType"
            label="chart"
            border
            size="small"
            class="toggle-btn"
            >温湿度变化曲线</el-radio
          >
        </div>
      </div>
      <template v-if="showType == 'table'">
        <div class="common-table" ref="table">
          <el-table
            :data="tableData"
            style="width: 100%"
            :max-height="tableHeight"
          >
            <el-table-column
              prop="tempHumidityTable"
              label="湿温度表"
              min-width="18%"
              align="center"
            />
            <el-table-column label="时间" min-width="30%" align="center">
              <template slot-scope="{ row }">
                {{ row.startTime + ' ~ ' + row.endTime }}
              </template>
            </el-table-column>
            <el-table-column
              prop="date"
              label="温度"
              min-width="20%"
              align="center"
            >
              <template slot-scope="{ row }">
                <span
                  style="color: #23b899"
                  v-text="rangeText(row, 'temp')"
                ></span>
              </template>
            </el-table-column>
            <el-table-column
              prop="date"
              label="湿度"
              min-width="20%"
              align="center"
            >
              <template slot-scope="{ row }">
                <span
                  style="color: #387dff"
                  v-text="rangeText(row, 'hum')"
                ></span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="common-pagination">
          <el-pagination
            background
            layout="prev, pager, next, sizes, jumper"
            :page-size="search.pageSize"
            :current-page.sync="search.pageNum"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </template>
      <template v-else-if="showType == 'chart'">
        <div class="history-chart">
          <div class="chart-btn-content">
            <el-radio
              class="chart-btn"
              size="small"
              v-for="(item, index) in chartBtn"
              :key="index"
              v-model="btnActive"
              :label="item.id"
              border
              @change="getChartData"
              >{{ item.tableName }}</el-radio
            >
          </div>
          <div class="chart" ref="chart">
            <div class="chart-empty" v-if="chartEmpty">暂无数据</div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import { dateChange } from '@/utils/validate';
import { commonGx, commonCj, commonParam } from '@/api/common';
import { getTempList, getTempChart, getTempPast } from '@/api/env';
export default {
  data() {
    return {
      tableHeight: 200,
      // 时间选择器
      time: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '班次甲',
            onClick(vm) {
              if (vm.minDate && vm.maxDate) {
                vm.handleTimeInput('00:00:00', 'min');
                vm.handleTimeInput('12:00:00', 'max');
              }
            },
          },
          {
            text: '班次乙',
            onClick(vm) {
              if (vm.minDate && vm.maxDate) {
                vm.handleTimeInput('12:00:00', 'min');
                vm.handleTimeInput('24:00:00', 'max');
              }
            },
          },
        ],
      },
      search: {
        gongxu: '细纱',
        cj: '五纺',
        ct: [],
        endTime: '',
        startTime: '',
        pageSize: 10,
        pageNum: 1,
      },
      searchRules: {
        ct: [{ required: true, message: '车台范围', trigger: 'change' }],
        startTime: [{ required: true, message: '时间', trigger: 'change' }],
      },
      total: 10,
      showType: 'table',
      equipOption: [],
      tableData: [],
      // chart
      chartEmpty: false,
      btnActive: 1,
      chartBtn: [],
      myChart: null,
      timeSource: [],
      temp: [],
      humidity: [],
    };
  },
  created() {
    let today = new Date(new Date(new Date().toLocaleDateString()).getTime());
    let yesterday = new Date(
      new Date(new Date().toLocaleDateString()).getTime() - 24 * 60 * 60 * 1000
    );
    this.time = [dateChange(yesterday), dateChange(today)];
    window.addEventListener('resize', this.getHeight);
    this.getCs(2);
  },
  computed: {
    cjOption() {
      return this.$store.getters.cjOption;
    },
    gxOption() {
      return this.$store.getters.gxOption;
    },
  },
  mounted() {
    document.getElementsByClassName(
      'el-pagination__jump'
    )[0].childNodes[0].nodeValue = '跳至';
    this.$nextTick(() => {
      this.getHeight();
    });
  },
  destroyed() {
    window.removeEventListener('resize', this.getHeight);
  },
  watch: {
    showType: function (val) {
      if (val == 'chart') {
        this.$nextTick(() => {
          let options = this.setOptions(
            this.timeSource,
            this.temp,
            this.humidity
          );
          this.chartInit(options);
        });
      }
    },
    time: function (val) {
      if (val) {
        this.search.startTime = val[0];
        this.search.endTime = val[1];
      } else {
        this.search.startTime = '';
        this.search.endTime = '';
      }
    },
  },
  methods: {
    // 获取车台范围（因为车台范围为必选，所以请求到列表后默认选中第一条）
    async getCs(val) {
      const equipData = await commonParam({ type: val });
      this.equipOption = equipData.data;
      this.search.ct.push(this.equipOption[0].dictCode);
      this.getTableData();
      this.getList();
    },
    async getTableData() {
      let form = Object.assign({}, this.search);
      for (let i in form) {
        if (!form[i]) {
          delete form[i];
        }
      }
      const res = await getTempPast(form);
      if (res.code == 1) {
        this.tableData = res.data.list;
        this.total = res.data.total;
      }
    },
    async getList() {
      const res = await getTempList({ ct: this.search.ct });
      if (res.code == 1) {
        this.chartBtn = res.data;
        this.btnActive = this.chartBtn[0]['id'];
        this.getChartData(this.btnActive);
      }
    },
    async getChartData(id) {
      this.loading = true;
      let form = {
        cj: this.search.cj,
        ct: this.search.ct,
        devSn: id,
        gongxu: this.search.gongxu,
        startTime: this.search.startTime,
        endTime: this.search.endTime,
      };
      const res = await getTempChart(form);
      if (res.code == 1) {
        this.chartEmpty = false;
        this.timeSource = [];
        this.temp = [];
        this.humidity = [];
        res.data.map((item) => {
          this.timeSource.push(item.time);
          this.temp.push(parseFloat(item.temp).toFixed(1));
          this.humidity.push(parseFloat(item.humidity).toFixed(1));
        });
        let options = this.setOptions(
          this.timeSource,
          this.temp,
          this.humidity
        );
        this.chartInit(options);
      } else {
        this.chartEmpty = true;
      }
      this.loading = false;
    },
    chartInit(options) {
      if (this.$refs.chart) {
        if (this.myChart == null) {
          this.myChart = this.$echarts.init(this.$refs.chart);
        } else {
          this.myChart.clear();
          this.myChart = this.$echarts.init(this.$refs.chart);
        }
        this.myChart.setOption(options);
      }
    },
    setOptions(time, temp, humidity) {
      let tempMax = 50;
      let humMax = 100;
      let option = {
        tooltip: {
          trigger: 'axis',
          textStyle: {
            fontSize: 13,
          },
          padding: 10,
          backgroundColor: 'rgba(66, 66, 89, 0.8)',
          formatter: function (params) {
            var result =
              '<div style="font-size:14px;font-weight:600;margin-bottom:4px">' +
              params[0].axisValue +
              '</div>';
            params.forEach(function (item, index) {
              result +=
                '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' +
                item.color +
                '"></span>';
              result += item.seriesName + '：' + item.data;
              let unit = item.seriesName == '温度' ? '℃' : '%';
              result += unit + '<br>';
            });
            return result;
          },
        },
        legend: {
          right: 10,
          data: ['温度', '湿度'],
          icon: 'circle',
        },
        grid: {
          left: '2%',
          right: '2%',
          // bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: true,
          data: time,
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: '#292B3D',
            fontSize: 12,
            formatter: function (value) {
              let time = value.split(' ');
              let year = time[0];
              let date = time[1];
              let result = year + '\n' + date;
              return result;
            },
          },
          axisLine: {
            lineStyle: { color: '#EAEBF0' },
          },
        },
        yAxis: [
          {
            type: 'value',
            min: 0,
            max: tempMax,
            splitNumber: 5,
            interval: tempMax / 5,
            axisTick: { show: false },
            axisLine: { show: false },
            axisLabel: {
              show: true,
              fontSize: 13,
              textStyle: {
                color: '#292B3D',
              },
              formatter: '{value}℃',
            },
            splitLine: {
              lineStyle: {
                color: '#EAEBF0',
                type: 'dotted',
              },
            },
          },
          {
            type: 'value',
            min: 0,
            max: humMax,
            splitNumber: 5,
            interval: humMax / 5,
            nameLocation: 'end',
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: {
              show: true,
              fontSize: 13,
              textStyle: {
                color: '#292B3D',
              },
              formatter: '{value}%',
            },
          },
        ],
        series: [
          {
            name: '温度',
            color: '#23B899',
            type: 'line',
            yAxisIndex: 0,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              borderWidth: 2,
              borderColor: '#fff',
            },
            data: temp,
          },
          {
            name: '湿度',
            color: '#387DFF',
            type: 'line',
            yAxisIndex: 1,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              borderWidth: 2,
              borderColor: '#fff',
            },
            data: humidity,
          },
        ],
      };
      return option;
    },
    getHeight() {
      this.tableHeight = this.$refs.table.offsetHeight;
    },
    searchNow() {
      this.$refs['search'].validate((valid, object) => {
        if (valid) {
          this.getTableData();
          this.getList();
        } else {
          let falseMsg = [];
          for (let i in object) {
            falseMsg.push(object[i][0].message);
          }
          falseMsg = falseMsg.join('、');
          this.$message({
            message: `请选择${falseMsg}`,
            iconClass: 'el-icon-warning',
            customClass: 'common-message',
          });
          return false;
        }
      });
    },
    rangeText(row, type) {
      if (type == 'temp') {
        let min = parseFloat(row.minTemp).toFixed(1);
        let max = parseFloat(row.maxTemp).toFixed(1);
        return min + ' ~ ' + max;
      } else {
        let min = parseFloat(row.minHumidity).toFixed(1) + '%';
        let max = parseFloat(row.maxHumidity).toFixed(1) + '%';
        return min + ' ~ ' + max;
      }
    },
    handleSizeChange(val) {
      this.search.pageNum = 1;
      this.search.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.search.pageNum = val;
      this.getTableData();
    },
  },
};
</script>

<style lang="stylus" scoped>
.common-wrapper {
  height: 100%;
}

.show-type {
  display: flex;
  flex-shrink: 0;
  margin-left: 10px;
}

.common-search {
  display: flex;
}

.common-search.el-form--inline .el-range-editor--small.el-input__inner {
  width: 340px;
}

.history-chart {
  height: calc(100% - 50px);
  display: flex;
  padding-top: 10px;

  .chart-btn-content {
    width: 260px;
    padding-right: 10px;
    overflow-y: auto;
    display: grid;
    grid-template-columns: repeat(2, 118px);
    grid-template-rows: repeat(auto-fill, 32px);
    grid-column-gap: 9px;
    grid-row-gap: 5px;
  }

  .chart {
    flex-grow: 1;
  }

  .chart-empty {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #5e6d82;
  }
}

::v-deep .toggle-btn.el-radio--small.is-bordered {
  padding: 0;
  width: 130px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-color: #387DFF;
  margin: 0 10px 0 0;

  .el-radio__input {
    display: none;
  }

  .el-radio__label {
    padding: 0;
    font-size: 14px;
    color: #387DFF;
  }

  &.is-checked {
    background: linear-gradient(90deg, #23B899 0%, #387DFF 100%);
    border-color: #fff;

    .el-radio__label {
      color: #fff;
    }
  }

  & +.el-radio.is-bordered {
    margin: 0;
  }
}

::v-deep .chart-btn.el-radio--small.is-bordered {
  padding: 0;
  width: 118px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: none;
  margin: 0 10px 0 0;
  background: #F3F4F6;

  .el-radio__input {
    display: none;
  }

  .el-radio__label {
    padding: 0;
    font-size: 14px;
    color: #292B3D;
  }

  &.is-checked {
    background: #2C67F6;
    border-color: #fff;

    .el-radio__label {
      color: #fff;
    }
  }

  & +.el-radio.is-bordered {
    margin: 0;
  }
}
</style>
